from selenium import webdriver
import datetime
import time
from selenium.webdriver.common.by import By

options = webdriver.ChromeOptions()
driver = webdriver.Chrome()
driver.maximize_window()

# 登录函数
def login():
    driver.get("https://www.taobao.com")
    time.sleep(3)

    if driver.find_element(By.LINK_TEXT, "亲，请登录"):
        driver.find_element(By.LINK_TEXT, "亲，请登录").click()
        print("请在20秒内完成登录")
        time.sleep(20)

        # 进入购物车
        driver.get("https://cart.taobao.com/cart.htm")
        time.sleep(3)
        if driver.find_element(By.ID, "J_SelectAll1"):
            driver.find_element(By.ID, "J_SelectAll1").click()
        
        now = datetime.datetime.now()
        print("login success:",now.strftime("%Y-%m-%d %H:%M:%S"))

def buy(buytime):
    while True:
        now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
        if now > buytime:
            try:
                if driver.find_element(By.ID, "J_Go"):
                   driver.find_element(By.ID, "J_Go").click()
                   time.sleep(0.5)
                   driver.find_element(By.LINK_TEXT, "提交订单").click()
                   print("恭喜你，购买成功！")
            except:
                time.sleep(0.1)
        else:
            print(now)
            time.sleep(0.1)

if __name__ == "__main__":
    login()
    buy("2023-09-17 11:49:30.000")